<?php

    class PostController extends HangveController
    {
        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete, replyDelete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users
                    'actions'=>array('index','view'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user
                    'actions'=>array('create', 'upload', 'createShop', 'updateShop', 'replyCreate'),
                    'users'=>array('@'),
                ),

                array('allow', // allow owner user
                    'actions'=>array('update'),
                    'users'=>array('@'),
                    'expression'    =>  array($this, 'ruleModOwnerPost'), 
                ), 
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('replyUpdate', 'replyDelete'),
                    'users'=>array('@'),
                    'expression'    =>  array($this, 'ruleModOwnerReply'), 
                ),
                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                    'actions'=>array('delete'),
                    'users'=>array('@'),
                    'expression'    =>  '$user->userInfo->isMod', 
                ),
                array('deny',  // deny all users 
                    'users'=>array('*'),
                ),
            );
        }

        public function ruleModOwnerPost($user){
            $id = Yii::app()->request->getQuery('id');
            return Post::model()->checkUserPermisstion($id);
        }

        public function ruleModOwnerReply($user){
            $reply_id = Yii::app()->request->getQuery('reply_id');
            return PostReply::model()->checkUserPermisstion($reply_id);
        }


        public function init(){
            parent::init();
        }


        public function actionReplyCreate($post_id, $reply_id = null)
        {   
            $model = new PostReply;
            $post = Post::model()->getModel($post_id, array('with' => array('cat', 'catParent')));

            if($postReplyData = Yii::app()->request->getPost('PostReply')){

                foreach($postReplyData as & $p){
                    $p = $p ? $p : null;
                }
                $model->attributes  = $postReplyData;

                $model->user_id = $this->user->id;
                if($model->reply_id){

                    $replyReply = PostReply::model()->getModel($model->reply_id);
                    if(!$replyReply || $replyReply->post_id != $model->post_id){
                        throw new CHttpException(500, 'Hành động trả lời không hợp lệ.');
                    }
                    $model->parent_id = $replyReply->parent_id ? $replyReply->parent_id : $replyReply->id;
                }
                $model->created = MyDateTime::getCurrentTime();
                $model->cat_parent_id = $post->cat_parent_id;;
                $model->cat_id = $post->cat_id;;

                if($model->validate()){

                    $model->insert();
                    PostCat::model()->updateReplyCount();
                    Post::model()->updateReplyCount($post->id);
                    Post::model()->updateByPk($post->id, array('upped' => MyDateTime::getCurrentTime())); 
                    
                    // upload images
                    $imgConf = Yii::app()->params->hangve['post'];
                    Yii::import('ext.wideimage.lib.WideImage');

                    $savedPath = $model->getImagePath();

                    // array map temp to saved
                    $imageArray = array();
                    if($imgTemp = Yii::app()->session['imgTempReply']){
                        foreach($imgTemp as $i => $imgPath){
                            if(!file_exists($imgPath)) continue;
                            $fileName = $post->alias.'_'.PostImage::model()->nextId;
                            $this->_saveTypeImage($imgPath, $imgConf, $savedPath, $fileName);

                            $imageArray['/'.$imgPath] = '/'.$savedPath.$fileName.'_large.jpg';

                            // delete image in temp
                            unlink($imgPath);

                            // insert to DB
                            $itemImage = new PostImage;
                            $itemImage->post_id = $post->id;
                            $itemImage->reply_id = $model->id;
                            $itemImage->user_id = $this->user->id;
                            $itemImage->image = $fileName;
                            $itemImage->is_cover = 0;
                            $itemImage->insert();
                        }
                        unset(Yii::app()->session['imgTempReply']);
                    }

                    // parse content
                    $content = $this->_parseContent($model, $post, $imgConf, $savedPath, $imageArray);

                    $model->content = $content;
                    $model->setIsNewRecord(false);
                    $model->filterAttributes();
                    $model->update();

                    Post::model()->elasticsearchIndex($post->id);
                    

                    Yii::app()->user->setFlash('success', Yii::t('app', 'Đăng trả lời thành công.'));

                    $this->redirect($model->post->url."#reply_{$model->id}");

                }
            }


            $content = Yii::app()->request->getPost('content');
            $post_id = Yii::app()->request->getPost('post_id');
            $reply_id = Yii::app()->request->getPost('reply_id');


            if(!Yii::app()->request->isPostRequest){
                throw new CHttpException(500, 'Hành động trả lời nâng cao chỉ chấp nhận khi được click từ 1 bài viết. Quay lại bài viết: '.
                    CHtml::link($post->title, $post->url));
            }

            $postReplyReply = null;
            if($reply_id){
                $postReplyReply = PostReply::model()->getModel($reply_id);
                if(!$postReplyReply || $postReplyReply->post_id != $post_id){
                    throw new CHttpException(500, 'Hành động trả lời không hợp lệ. Quay lại bài viết: '.
                        CHtml::link($post->title, $post->url));
                }
            }

            $model->post_id = $post->id;
            $model->reply_id = $reply_id;
            $model->content = $content;

            $this->catSelected = $post->catParent->alias;
            $this->render('reply_create', compact(
                'model',
                'post',
                'postReplyReply'
            ));
        }

        public function actionReplyUpdate($reply_id)
        {   
            $model = PostReply::model()->getModel($reply_id, array('with' => array('post' => array('with' => array('cat', 'catParent')))));

            if($postReplyData = Yii::app()->request->getPost('PostReply')){

                foreach($postReplyData as & $p){
                    $p = $p ? $p : null;
                }
                $model->attributes  = $postReplyData;

                $model->user_id = $this->user->id;
                if($model->reply_id){

                    $replyReply = PostReply::model()->getModel($model->reply_id);
                    if(!$replyReply || $replyReply->post_id != $model->post_id){
                        throw new CHttpException(500, 'Hành động trả lời không hợp lệ.');
                    }
                    $model->parent_id = $replyReply->parent_id ? $replyReply->parent_id : $replyReply->id;
                }
                $model->changed = MyDateTime::getCurrentTime();

                if($model->validate()){

                    // upload images
                    $imgConf = Yii::app()->params->hangve['post'];
                    Yii::import('ext.wideimage.lib.WideImage');

                    $savedPath = $model->getImagePath();

                    // parse content
                    $content = $this->_parseContent($model, $model->post, $imgConf, $savedPath);
                    
                    $model->content = $content;
                    $model->setIsNewRecord(false);
                    $model->update();
                    
                    //Post::model()->updateByPk($model->post_id, array('upped' => MyDateTime::getCurrentTime()));
                    Post::model()->elasticsearchIndex($model->post_id);
                
                
                    Yii::app()->user->setFlash('success', Yii::t('app', 'Sửa trả lời thành công.'));

                    $this->redirect($model->post->url."#reply_{$model->id}");

                }
            }

            $post = $model->post;
            $postReplyReply = $model->postReplyReply;
            $this->catSelected = $post->catParent->alias;
            $this->render('reply_update', compact(
                'model',
                'post',
                'postReplyReply'
            ));
        }

        public function actionReplyDelete($reply_id)
        {   
            $model = PostReply::model()->getModel($reply_id);
            $post = $model->post;

            if($model->postRepliesByReply){
                foreach($model->postRepliesByReply as $_postReply){
                    //$_postReply->reply_id = null;
                    $_postReply->reply_id = $_postReply->parent_id;
                    $_postReply->update();    
                }     
            }
            if($model->postRepliesByParent){
                foreach($model->postRepliesByParent as $_postReply){
                    if($model->id == $_postReply->reply_id){
                        $_postReply->parent_id = null;
                        $_postReply->reply_id = null;
                    }else{
                        $_postReply->parent_id = ($_postReply->postReplyReply && $_postReply->postReplyReply->parent_id) ? $_postReply->postReplyReply->parent_id : $_postReply->reply_id;   
                    }
                    $_postReply->update();    
                }     
            }

            PostImage::model()->deleteAllByAttributes(array('reply_id' => $model->id));
            $model->deleteFiles(); 
            $model->delete();
            Post::model()->elasticsearchIndex($post);
            
            PostCat::model()->updateReplyCount();
            Post::model()->updateReplyCount($post->id);

            //            Yii::app()->user->setFlash('info', 'Xóa trả lời thành công.');
            //            $this->redirect($post->url);
        }

        private function _ajaxPostReply($postReplyModel, $post){
            if($postReplyPost = Yii::app()->request->getPost('PostReply')){
                foreach($postReplyPost as & $p){
                    $p = $p ? $p : null;
                }
                $postReplyModel->attributes  = $postReplyPost;
                if($postReplyModel->reply_id){
                    $postReplyReply = PostReply::model()->findByPk($postReplyModel->reply_id);
                    if(!$postReplyReply || $postReplyReply->post_id != $post->id){
                        throw new CHttpException(500, 'Hành động trả lời không hợp lệ. Quay lại bài viết: '.
                            CHtml::link($post->title, $post->url));
                    }
                    $postReplyModel->parent_id = $postReplyReply->parent_id ? $postReplyReply->parent_id : $postReplyReply->id;
                }

                $postReplyModel->created = MyDateTime::getCurrentTime();
                $postReplyModel->cat_parent_id = $post->cat_parent_id;;
                $postReplyModel->cat_id = $post->cat_id;;
                if($postReplyModel->validate()){

                    $postReplyModel->insert();  
                    PostCat::model()->updateReplyCount();
                    $post->updateReplyCount();
                    Post::model()->updateByPk($postReplyModel->post_id, array('upped' => MyDateTime::getCurrentTime())); 

                    // parse content
                    $savedPath = $postReplyModel->getImagePath();
                    Yii::import('ext.wideimage.lib.WideImage');
                    $imgConf = Yii::app()->params->hangve['post'];
                    
                    $content = $this->_parseContent($postReplyModel, $post, $imgConf, $savedPath);                    

                    $postReplyModel->content = $content;
                    $postReplyModel->setIsNewRecord(false);
                    $postReplyModel->filterAttributes();
                    $postReplyModel->update();

                    Post::model()->elasticsearchIndex($post->id);
                    
                    $dataReturn = array(
                        'status' => 'success',
                        'message' => 'Gửi trả lời thành công viết thành công',
                        'replyView' => $this->renderPartial('_reply_view', array('postReply' => $postReplyModel), true),
                        'postReply' => $postReplyModel->attributes,
                        'afterSelector' => $postReplyModel->parent_id ? "[reply_parent_id={$postReplyModel->parent_id}]:last" : "[post_id={$postReplyModel->post_id}]:last", 
                    );
                    echo json_encode($dataReturn);
                    Yii::app()->end();     
                }
            }
        }

        /**
        * Displays a particular model.
        * @param integer $id the ID of the model to be displayed
        */
        public function actionView($id)
        {
            $post = Post::model()->getModel($id, array('with' => array('cat', 'catParent')));

            $postReplyModel = new PostReply;
            $postReplyModel->post_id = $post->id;
            $postReplyModel->user_id = $this->user ? $this->user->id : null;

            if(Yii::app()->request->isAjaxRequest){
                $this->_ajaxPostReply($postReplyModel, $post);
            }


            $post->view_count++;
            $post->view_count_month++;
            $post->update();

            $imgConf = Yii::app()->params->hangve['post'];
            $uploadEditorPath = '';
            if($this->user){
                $uploadEditorPath = "{$imgConf['tempPathReply']}{$this->user->id}";
                Myext::createDir($uploadEditorPath); 
            }


            $postReplyData = array();
            $postReplyCount = 0;
            foreach($post->postReplies(array(
                'with' => array('postReplyReply'),
                'order' => 'postReplies.parent_id ASC, postReplies.created ASC'
                )) as $postReply){
                $postReplyCount++;
                if(!$postReply->parent_id){
                    $postReplyData[$postReply->id] = $postReply;    
                }else{
                    $postReplyData[$postReply->parent_id]->childs[$postReply->id] = $postReply;
                }           
            }

            $this->catSelected = $post->catParent->alias;  

            $this->render('view', compact(
                'post', 
                'postReplyModel',
                'uploadEditorPath',
                'postReplyData',
                'postReplyCount'
            ));
        }


        public function actionIndex($parent_alias, $child_alias = null){
            if(isset($_GET['index'])){
                Post::model()->elasticsearchIndex('all');
                $this->redirect(preg_replace('{(&|\?)index}','', Yii::app()->request->requestUri));
            }

            $page = Yii::app()->request->getQuery('trang', 1);


            $model = new Post('search');
            //$model->unsetAttributes();

            $cats = PostCat::model()->getDataAll();

            if(empty($cats[$parent_alias])){
                throw new CHttpException(404, 'Yêu cầu không hợp lệ');
            }
            $this->catSelected = $parent_alias; 

            $catParent = $cats[$parent_alias];
            $catChild = !empty($cats[$parent_alias]['cats'][$child_alias]) ? $cats[$parent_alias]['cats'][$child_alias] : null;
            $catChildKey = $catChild ? $catChild['alias'] : 'all';

            //            echo '<pre>';print_r($catParent);echo '</pre>';
            //            echo '<pre>';print_r($catChild);echo '</pre>';die;


            $filtersEncode = (string)Yii::app()->request->cookies['filters'];
            $filters = json_decode($filtersEncode, true);
            $filters = $filters ? $filters : array();

            if($catChild){
                $model->cat_id = $catChild['id'];
                $model->cat_alias = $catChild['alias'];
            }

            if($filters && !empty($filters[$catParent['alias']][$catChildKey])){
                $model->attributes = $filters[$catParent['alias']][$catChildKey]; 
            }elseif($this->city){
                $model->city_alias = $this->city['alias'];
                $model->city_id = $this->city['id'];
            }

            //            echo '<pre>';print_r($filters[$catParent['id']][$catChildKey]);echo '</pre>';
            //            echo '<pre>';print_r($model->sort);echo '</pre>';
            //            echo '<pre>';print_r($model->city_alias);echo '</pre>';
            //            echo '<pre>';print_r($model->district_alias);echo '</pre>';
            //            echo '<pre>';print_r($model->type);echo '</pre>';
            //            echo '<pre>';print_r($model->state);echo '</pre>';
            //            echo '<pre>';print_r($model->price_from);echo '</pre>';
            //            echo '<pre>';print_r($model->price_to);echo '</pre>';
            //            echo '<pre>';print_r($model->area_use_about);echo '</pre>';
            //            echo '<pre>';print_r($model->area_floor_about);echo '</pre>';
            //            echo '<pre>';print_r($model->status);echo '</pre>';
            //            echo '<pre>';print_r($model->is_all_city);echo '</pre>';
            //            echo '<pre>';print_r($model->has_image);echo '</pre>';

            //            if(!Yii::app()->request->isAjaxRequest){
            //                $this->redirect($this->createUrl('/hangve/post/index', array('parent_alias' => $parent_alias, 'alias' => $catChild ? $catChild ['alias'] : null)), true, 301);    
            //            }

            
            

            // set attributes to model & validate
            if($sort = Yii::app()->request->getQuery('sap-xep')){

                $model->sort = in_array($sort, array_keys($model->sortMapping)) ? $sort : $model->sort;

                $model->keyword = Yii::app()->request->getQuery('tim-kiem');

                $model->cat_alias = in_array($child_alias, array_keys($catParent['cats'])) ? $child_alias : $model->cat_alias;

                $city_alias = Yii::app()->request->getQuery('thanh-pho');
                if($city_alias){
                    $model->city_alias = in_array($city_alias, array_keys($this->cities)) ? $city_alias : $this->city['alias'];
                    Yii::app()->webData->setCity($model->city_alias);

                    $district_alias = Yii::app()->request->getQuery('quan');
                    $model->district_alias = in_array($district_alias, array_keys($this->cities[$model->city_alias]['districts'])) ? $district_alias : null;
                }

                $type = Yii::app()->request->getQuery('loai-tin');
                $model->type = in_array($type, array_keys($model->typeData)) ? $type : null;

                $state = Yii::app()->request->getQuery('tinh-trang');
                $model->state = in_array($state, array_keys($model->stateData)) ? $state : null;

                $price_from = Yii::app()->request->getQuery('gia-tu');
                $model->price_from = in_array($price_from, array_keys($model->priceData)) ? $price_from : null;

                $price_to = Yii::app()->request->getQuery('gia-den');
                $model->price_to = in_array($price_to, array_keys($model->priceData)) ? $price_to : null;
                if(($model->price_from && $model->price_to) && $model->price_to <= $model->price_from) $model->price_to = null;

                $area_use_about = Yii::app()->request->getQuery('dien-tich-su-dung');
                $model->area_use_about = in_array($area_use_about, array_keys($model->areaAboutData)) ? $area_use_about : null;

                $area_floor_about = Yii::app()->request->getQuery('dien-tich-mat-bang');
                $model->area_floor_about = in_array($area_floor_about, array_keys($model->areaAboutData)) ? $area_floor_about : null;
                if($model->area_use_about && $model->area_floor_about){
                    if($model->getAreaAboutKeyIndex($model->area_use_about) < $model->getAreaAboutKeyIndex($model->area_floor_about)){
                        $model->area_floor_about = null;   
                    }
                }

                $status = Yii::app()->request->getQuery('trang-thai');
                $model->status = in_array($status, array_keys($model->statusData)) ? $status : null;

                $has_image = Yii::app()->request->getQuery('co-anh');
                $model->has_image = !$has_image ? 0 : 1;

                $is_all_city = Yii::app()->request->getQuery('toan-quoc');
                $model->is_all_city = !$is_all_city ? 0 : 1;

            }

            // save filters
            $filters[$catParent['alias']][$catChildKey]['sort'] = $model->sort;
            $filters[$catParent['alias']][$catChildKey]['city_alias'] = $model->city_alias;
            $filters[$catParent['alias']][$catChildKey]['district_alias'] = $model->district_alias;
            $filters[$catParent['alias']][$catChildKey]['type'] = $model->type;
            $filters[$catParent['alias']][$catChildKey]['state'] = $model->state;
            $filters[$catParent['alias']][$catChildKey]['price_from'] = $model->price_from;
            $filters[$catParent['alias']][$catChildKey]['price_to'] = $model->price_to;
            $filters[$catParent['alias']][$catChildKey]['area_use_about'] = $model->area_use_about;
            $filters[$catParent['alias']][$catChildKey]['area_floor_about'] = $model->area_floor_about;
            $filters[$catParent['alias']][$catChildKey]['status'] = $model->status;
            $filters[$catParent['alias']][$catChildKey]['is_all_city'] = $model->is_all_city;
            $filters[$catParent['alias']][$catChildKey]['has_image'] = $model->has_image;
            Yii::app()->request->cookies['filters'] = new CHttpCookie('filters', json_encode($filters));

            $toogleFilterOpen = false;
            if(empty($filters[$catParent['alias']][$catChildKey]['visible'])){
                $toogleFilterOpen = false;    
            }elseif($model->keyword
            ||  $model->district_alias
            ||  $model->type
            ||  $model->state
            ||  $model->price_from
            ||  $model->price_to
            ||  $model->area_use_about
            ||  $model->area_floor_about
            ||  $model->status
            ||  $model->is_all_city
            ||  $model->has_image
            ) $toogleFilterOpen = true;



            // search
            $client = Post::model()->elasticClient;
            
            $searchParams = array(
                'index' => IS_LOCAL ? 'hangve_local' : 'hangve',
                'type' => 'post',
            );
            
//            $retType = $client->indices()->getMapping($searchParams);
//            echo '<pre>';print_r($retType);echo '</pre>';die;
            
            $filter = array();

            $filter[]['term']['cat_parent_alias'] = $catParent['alias'];
            
            if($model->cat_alias)       $filter[]['term']['cat_alias'] = $model->cat_alias;
            if($model->city_alias)      $filter[]['term']['city_alias'] = $model->city_alias;
            if($model->district_alias)  $filter[]['term']['district_alias'] = $model->district_alias;
            if($model->type)            $filter[]['term']['type'] = strtolower($model->type);
            if($model->state)           $filter[]['term']['state'] = strtolower($model->state);
            if($model->status)          $filter[]['term']['status'] = strtolower($model->status); 
            if($model->is_all_city)     $filter[]['term']['is_all_city'] = $model->is_all_city;


            if($model->price_from && $model->price_to && $model->price_from < $model->price_to){
                $filter[]['range']['price']['gte'] = $model->price_from;
                $filter[]['range']['price']['lte'] = $model->price_to;
            }
            elseif($model->price_from)  $filter[]['range']['price']['gte'] = $model->price_from;
            elseif($model->price_to)    $filter[]['range']['price']['lte'] = $model->price_to;

            if($model->sort == 'price') $filter[]['range']['price']['gt'] = 0;
            if($model->has_image)       $filter[]['range']['image_count']['gt'] = 0;

            if($model->area_use_about && $model->area_floor_about){
                list($use_from, $use_to) = $model->getAreaAboutFromTo($model->area_use_about);
                list($floor_from, $floor_to) = $model->getAreaAboutFromTo($model->area_floor_about);
                $filter[]['query_string']['query'] = "area_use:[{$use_from} TO {$use_to}] OR area_floor:[{$floor_from} TO {$floor_to}]";  
            }
            elseif($model->area_use_about){
                list($use_from, $use_to) = $model->getAreaAboutFromTo($model->area_use_about);
                $filter[]['query_string']['query'] = "area_use:[{$use_from} TO {$use_to}]";  
            }
            elseif($model->area_floor_about){
                list($floor_from, $floor_to) = $model->getAreaAboutFromTo($model->area_floor_about);
                $filter[]['query_string']['query'] = "area_floor:[{$floor_from} TO {$floor_to}]"; 
            } 

            $query = array();
            if($model->keyword = trim($model->keyword)){
                $query['multi_match']['query'] = $model->keyword;
                $query['multi_match']['fields'] = array('title^2', 'title_unsigned');
            } else{
                $query['match_all'] = array();
            }

            $pageSize = 5;

            $searchParams['body'] = array(
                "from" => ($page - 1) * $pageSize, 
                "size" => $pageSize,
                'query' => array(
                    'filtered' => array(
                        "filter" => $filter ? array('and' => $filter) : array(),
                        "query"  => $query
                    )
                ),
                // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html
                'sort' => array(
                    array(
                        $model->sortMapping[$model->sort] => array(
                            'order' => in_array($model->sortMapping[$model->sort], array('price')) ? 'asc' : 'desc',
                        ),
                    )    
                ),    
            ); 
//            echo '<pre>';print_r($searchParams);echo '</pre>';

            //$searchParams['body']['query']['filtered']['filter'] = array();
            //            unset($searchParams['body']['query']['filtered']['filter']['and'][2]);
            //            unset($searchParams['body']['query']['filtered']['filter']['and'][1]);

            //            $a = json_encode($searchParams['body']);
            //            echo '<pre>';print_r($a);echo '</pre>';


            try{
                $results = $client->search($searchParams);
            }catch(Exception $e){
                throw new CHttpException('500', 'Hệ thống đang nâng cấp');
            }


//            echo '<pre>';print_r($searchParams);echo '</pre>';
//            echo '<pre>';print_r($results);echo '</pre>';die;

            $total = !empty($results['hits']['total']) ? $results['hits']['total'] : 0;
            $hits = !empty($results['hits']['hits']) ? $results['hits']['hits'] : array();
            unset($results);
            $postData = array();
            foreach($hits as $hit){
                $postData[] = $hit['_source'];    
            }
            unset($hits);


            $dataProvider = new CArrayDataProvider(array(), array(
                'totalItemCount' => $total,
                'pagination' => array(
                    'pageSize' => $pageSize,
                    'itemCount' => $total,
                    'pageVar' => 'trang',
                ),
            ));
            $dataProvider->setData($postData);
            $districtData = $model->city_alias ? District::model()->getDataByCity($model->city_alias) : array();
            $typeData = Post::model()->getTypeData($catParent['type'] == 'IMMOVABLE');

            $titleArray = array();
            $titleArray['catParentTitle'] = $catParent['name'];
            $titleArray['catTitle'] = !empty($catChild['name']) ? " {$catChild['name']}" : '';
            $titleArray['sortTitle'] = !empty($model->sort) ? " {$model->sortData[$model->sort]}" : '';
            $titleArray['locationTitle'] = empty($model->city_alias) ? " toàn quốc" : ($model->district_alias ? " {$this->cities[$model->city_alias]['districts'][$model->district_alias]['name']} - {$this->cities[$model->city_alias]['name']}" : " {$this->cities[$model->city_alias]['name']}");
            $titleArray['typeTitle'] = !empty($model->type) ? ", loại tin: {$model->typeData[$model->type]}" : '';
            $titleArray['stateTitle'] = !empty($model->state) ? ", tình trạng: {$model->stateData[$model->state]}" : '';
            $titleArray['priceTitle'] = '';
            if($model->price_from && $model->price_to && $model->price_from < $model->price_to){
                $titleArray['priceTitle'] = ", giá từ {$model->getPriceLabel($model->price_from)} đến {$model->getPriceLabel($model->price_to)}";
            }elseif($model->price_from){
                $titleArray['priceTitle'] = ", giá từ {$model->getPriceLabel($model->price_from)}";    
            }elseif($model->price_to){
                $titleArray['priceTitle'] = ", giá tối đa {$model->getPriceLabel($model->price_to)}";
            }
            $titleArray['statusTitle'] = !empty($model->status) ? ", trạng thái: {$model->statusData[$model->status]}" : '';
            $titleArray['areaUseTitle'] = !empty($model->area_use_about) ? ", diện tích sử dụng: {$model->areaAboutData[$model->area_use_about]}" : '';
            $titleArray['areaFloorTitle'] = !empty($model->area_floor_about) ? ", diện tích mặt bằng: {$model->areaAboutData[$model->area_floor_about]}" : '';
            $titleArray['hasImageTitle'] = !empty($model->has_image) ? ', có ảnh' : '';
            $titleArray['isAllCityTitle'] = !empty($model->is_all_city) ? ', toàn quốc' : '';
            $titleArray['keywordTitle'] = !empty($model->keyword) ? ", từ khóa {$model->keyword}" : '';

            foreach($titleArray as $k => & $v){
                if(!in_array($k, array('locationTitle', 'catParentTitle'))){
                    $v = mb_convert_case($v, MB_CASE_LOWER, 'UTF-8');      
                }        
            }
            $title = implode('', $titleArray);

            // TODO: SEO
            $catDesc = !empty($catChild['desc']) ? $catChild['desc'] : (!empty($catParent['desc']) ? $catParent['desc'] : null);

            $this->pageTitle = $title;
            $this->pageDesc = $title.' '.$catDesc;
            
            

            $this->render('index', compact('dataProvider'
                , 'model'
                , 'catParent'
                , 'catChild'
                , 'districtData'
                , 'typeData'
                , 'cats'
                , 'toogleFilterOpen'
                , 'catDesc'
            ));
        }


        public function actionCreate(){
            $model=new Post('create');
            $model->setIsNewRecord(TRUE);
            $model->show_map = 1;
            $model->status = 'dang-ban';


            if($post = Yii::app()->request->getPost('Post')){
                Yii::import('ext.TextParser');

                foreach($post as & $p){
                    $p = $p ? $p : null;
                }
                $model->attributes  = $post;

                $model->alias = TextParser::toSEOString($post['title']);
                $model->cat_parent_id = PostCat::model()->findByPk($post['cat_id'])->parent_id;
                $model->user_id = $this->user->id;
                if($model->validate()){

                    $model->price = $model->price ? str_replace('.', '', $model->price) : null;
                    $model->area_use = $model->area_use ? str_replace('.', '', $model->area_use) : null;
                    $model->area_floor = $model->area_use ? str_replace('.', '', $model->area_floor) : null;

                    $cover = Yii::app()->request->getPost('cover');
                    $model->created = $model->upped = MyDateTime::getCurrentTime();
                    $model->insert();
 
                    // upload images
                    $imgConf = Yii::app()->params->hangve['post'];
                    Yii::import('ext.wideimage.lib.WideImage');

                    $savedPath = $model->getImagePath();

                    // array map temp to saved
                    $imageArray = array();
                    $cover_setted = false;
                    $image_count = 0;
                    if($imgTemp = Yii::app()->session['imgTemp']){
                        foreach($imgTemp as $i => $imgPath){
                            if(!file_exists($imgPath)) continue;

                            // set cover
                            $imgPathInfo = pathinfo($imgPath);
                            $is_cover = 0;
                            if($cover){
                                if($cover == $imgPathInfo['filename']){
                                    $is_cover = 1; 
                                    $cover_setted = true;     
                                }  
                            }else{
                                if($i == 0){
                                    $is_cover = 1;
                                    $cover_setted = true;        
                                }
                            }
                            $fileName = $model->alias.'_'.PostImage::model()->nextId;   
                            if($is_cover){
                                $model->image = $fileName;
                            }

                            $this->_saveTypeImage($imgPath, $imgConf, $savedPath, $fileName);

                            $imageArray['/'.$imgPath] = '/'.$savedPath.$fileName.'_large.jpg';

                            // delete image in temp
                            unlink($imgPath);

                            // insert to DB
                            $itemImage = new PostImage;
                            $itemImage->post_id = $model->id;
                            $itemImage->user_id = $this->user->id;
                            $itemImage->image = $fileName;
                            $itemImage->is_cover = $is_cover;
                            $itemImage->insert();
                            $image_count++;
                        }
                        unset(Yii::app()->session['imgTemp']);
                    }

                    // parse content
                    $content = $this->_parseContent($model, null, $imgConf, $savedPath, $imageArray, $cover_setted, $image_count);

                    $model->content = $content;
                    $model->image_count = $image_count;

                    $model->filterAttributes();
                    $model->setIsNewRecord(false);
                    $model->update();

                    $model->elasticsearchIndex();

                    Yii::app()->user->setFlash('success', Yii::t('app', 'Đăng bài viết thành công.'));


                    PostCat::model()->updatePostCount();
                    unset(Yii::app()->request->cookies['post_saved']);
                    $this->redirect($model->getUrl('view'));

                }
            }

            
            // load post attributes from cookie
            $postSaved = (string)Yii::app()->request->cookies['post_saved'];
            $coverSaved = null;
            if($postSaved){
                $postAttributes = json_decode($postSaved, true);
                $coverSaved = !empty($postAttributes['cover']) ? $postAttributes['cover'] : null;
                $model->attributes = $postAttributes;
            }
            
            
            if(!$model->city_id) $model->city_id = $this->city['id'];
            $district_data = District::model()->getDataByCity($model->city_id, 'id');
            
            $this->render('create', compact(
                'model',
                'district_data',
                'coverSaved'
            ));
        }

        public function actionUpdate($id){
            $model = Post::model()->getModel($id);
            $model->scenario = 'update';
            $model->price = $model->priceFormat;
            $model->area_use = $model->areaUseFormat;
            $model->area_floor = $model->areaFloorFormat;


            if($post = Yii::app()->request->getPost('Post')){
                Yii::import('ext.TextParser');

                foreach($post as & $p){
                    $p = $p ? $p : null;
                }
                $model->attributes  = $post;

                //                $model->alias = TextParser::toSEOString($post['title']);
                $model->cat_parent_id = PostCat::model()->findByPk($post['cat_id'])->parent_id;


                if($model->validate()){

                    $model->price = $model->price ? str_replace('.', '', $model->price) : null;
                    $model->area_use = $model->area_use ? str_replace('.', '', $model->area_use) : null;
                    $model->area_floor = $model->area_use ? str_replace('.', '', $model->area_floor) : null;

                    $model->alias = TextParser::toSEOString($model->title);
                    $model->image = null;

                    $cover_id = Yii::app()->request->getPost('cover');
                    $cover_setted = false;     
                    if($cover_id){
                        $postImage = PostImage::model()->findByPk($cover_id);
                        if($postImage){

                            PostImage::model()->updateAll(array('is_cover' => 0), "post_id = {$model->id}");

                            $postImage->is_cover = 1;
                            $postImage->update(); 

                            $model->image = $postImage->image;
                            $cover_setted = true;  
                        }

                    }elseif(!$cover_id && !empty($model->postImages[0])){
                        $firstPostImage = $model->postImages[0];
                        $firstPostImage->is_cover = 1;
                        $firstPostImage->update();    

                        $model->image = $firstPostImage->image; 
                        $cover_setted = true;  
                    }
                    $model->changed = $model->upped = MyDateTime::getCurrentTime();
                    $model->update();

                    // upload images
                    $imgConf = Yii::app()->params->hangve['post'];
                    Yii::import('ext.wideimage.lib.WideImage');

                    $savedPath = $model->getImagePath();

                    // parse content
                    $content = $this->_parseContent($model, null, $imgConf, $savedPath, array(), $cover_setted);
                    $model->content = $content;
                    
                    $model->filterAttributes();
                    $model->update();

                    $model->elasticsearchIndex();
                    PostCat::model()->updatePostCount();

                    Yii::app()->user->setFlash('success', Yii::t('app', 'Sửa bài viết thành công'));

                    $this->redirect($model->getUrl('view'));

                }
            }

            if(!$model->city_id) $model->city_id = $this->city['id'];
            $district_data = District::model()->getDataByCity($model->city_id, 'id');

            $this->render('update', compact(
                'model',
                'district_data'
            ));
        }

        /**
        * Deletes a particular model.
        * If deletion is successful, the browser will be redirected to the 'admin' page.
        * @param integer $id the ID of the model to be deleted
        */
        public function actionDelete($id)
        {
            $model = Post::model()->getModel($id);
            Myext::deleteDir($model->getImagePath());
            $model->delete();
            $model->elasticsearchDelete();

            //            if($model->fb_posted_id){

            //                $fbPageId = Yii::app()->params->user['fb']['pageId'];

            //                Yii::import('ext.facebook.src.Facebook');
            //                $fb = new Facebook(array(
            //                    'appId'  => Yii::app()->params->user['fb']['appId'],
            //                    'secret' => Yii::app()->params->user['fb']['secret'],
            //                ));

            //                $fb_id = $fb->getUser();

            // check login
            //                $fbLoginUrl = $fb->getLoginUrl(array(
            //                    'scope' => 'publish_stream,manage_pages',
            //                    'redirect_uri' => Yii::app()->request->getBaseUrl(TRUE).Yii::app()->request->requestUri,
            //                ));
            //                if(!$fb_id){
            //                    Yii::app()->controller->redirect($fbLoginUrl);
            //                }

            // check permissons
            //                $permissions = $fb->api("/me/permissions");
            //                if( 
            //                    !$fb_id || ! array_key_exists('publish_stream', $permissions['data'][0])
            //                    || ! array_key_exists('manage_pages', $permissions['data'][0])
            //                ) {
            //                    Yii::app()->controller->redirect($fbLoginUrl);
            //                }


            //                $fb->api("/{$model->fb_posted_id}","DELETE");
            //            }
        }
        
        private function _parseContent($model, $post = null, $imgConf, $savedPath, $imageArray = array(), $cover_setted = true, &$image_count = 0){
            $content = trim($model->content);
            Yii::import('ext.simple_html_dom');
            $html = new simple_html_dom($content);
            $externalSaved = array();
            if(Yii::app()->params->hangve['post']['download-external']){
                foreach($html->find('img') as $i => $img){
                    $img->alt = $this->domain.' : '.CHtml::encode(isset($model->title) ? $model->title : $post->title);

                    if(!empty($imageArray[$img->src])){
                        $img->src = $imageArray[$img->src]; 
                        continue; 
                    }
                    if(in_array($img->src, array_keys($externalSaved))){
                        $img->src = $externalSaved[$img->src];
                        continue;   
                    }

                    if(preg_match('{^https?.+$}six', $img->src) && strpos($img->src, $this->baseUrl) === FALSE){
                        $fileName = $model->alias.'_'.PostImage::model()->nextId;
                        $size = Myext::getWidthHeightImage($img->src);
                        if(!$size) $size = Myext::getWidthHeightImage($img->src, 0);

                        if(!$size || ($size && $size['width'] > 200 && $size['height'] > 150)){
                            $source = $img->src;
                            $this->_saveTypeImage($img->src, $imgConf, $savedPath, $fileName);
                            $img->src = '/'.$savedPath.$fileName.'_large.jpg';
                            $img->width = null;
                            $img->height = null;

                            // insert to DB 
                            $itemImage = new PostImage;
                            $itemImage->post_id = $model->id;
                            $itemImage->user_id = $this->user->id;
                            $itemImage->image = $fileName;
                            $itemImage->is_cover = 0;

                            if(!$cover_setted && $i == 0){
                                $itemImage->is_cover = 1;
                                $model->image = $fileName;
                                $cover_setted = true;    
                            }

                            $itemImage->insert();
                            $image_count++;
                            
                            $externalSaved[$source] = $img->src;
                        }
                    }
                }
            }

            foreach($html->find('a') as $a){
                if(preg_match('{^https?.+$}six', $a->href) && strpos($a->href, $this->baseUrl) === FALSE){
                    $a->rel = 'nofollow';
                    $a->target = '_blank';
                }
            }
            $content = $html->save();
            $html->clear();
            return $content;
        }

        private function _saveTypeImage($imgPath, $imgConf, $savedPath, $fileName){
            $imgObjInput = WideImage::load($imgPath);
            Myext::createDir($savedPath);
            foreach($imgConf['img'] as $type => $imgInfo){
                $imgObj = $imgObjInput;
                if(in_array($type, array('large', 'small'))){
                    $imgObj = $imgObj->resize(NULL, $imgInfo['height'], 'outside', 'down');
                    $imgObj = $imgObj->crop('center', 'center', $imgInfo['width'], $imgInfo['height']);  
                }else{
                    $imgObj = $imgObj->resize($imgInfo['width'], $imgInfo['height'], 'outside', 'down');
                    $imgObj = $imgObj->resizeCanvas($imgInfo['width'], $imgInfo['height'],'center','center', null, 'down');
                }

                if($imgInfo['watermark']){
                    // add bg
                    $color = 'f2f2f2';
                    $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
                    $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);

                    // add watermark
                    $watermark = WideImage::load($imgConf['watermark']['file']);
                    $imgObj = $imgObj->merge($watermark, $imgConf['watermark']['left'], $imgConf['watermark']['top'], $imgConf['watermark']['opacity']); 
                }
                $imgObj->saveToFile($savedPath.$fileName.'_'.$type.'.jpg', $imgInfo['quality']);
                unset($imgObj); 
            }
        }


        public function actionUpload(){  
            $type = Yii::app()->request->getQuery('type');
            $sessionKey = ($type == 'post') ? 'imgTemp' : 'imgTempReply';

            switch ($_SERVER['REQUEST_METHOD']) {
                //            case 'OPTIONS':
                //            case 'HEAD':
                //                $this->head();
                //                break;
                case 'GET':
                    $this->_uploadGet($type, $sessionKey);
                    break;
                case 'PATCH':
                case 'PUT':
                case 'POST':
                    $this->_uploadPost($type, $sessionKey);
                    break;
                case 'DELETE':
                    $this->_uploadDelete($type, $sessionKey);
                    break;
                default:
                    $this->header('HTTP/1.1 405 Method Not Allowed');
            }
        }

        private function _uploadPost($type, $sessionKey){
            //ini_set('upload_max_filesize', '1M');

            // check file size
            $maxUpload = (int)(ini_get('upload_max_filesize')); // Mb
            $maxFileSize = 10; // Mb
            $maxFileSize = ($maxUpload < $maxFileSize) ? $maxUpload : $maxFileSize;
            //            echo '<pre>';print_r($maxUpload);echo '</pre>';
            //            echo '<pre>';print_r($_FILES["files"]);echo '</pre>';die;
            // Check the upload
            if (!isset($_FILES["files"]) || !$_FILES["files"]["size"][0] || $_FILES["files"]["size"][0] > $maxFileSize * 1024000 || !in_array($_FILES["files"]["type"][0], array(
                'image/gif',
                'image/jpeg',
                'image/png',
                'image/bmp',
            ))){
                $data = array(
                    'files' => array(
                        array(
                            'name' => $_FILES["files"]["name"][0],
                            'size' => $_FILES["files"]["size"][0],
                            'type' => $_FILES["files"]["type"][0],
                            'error' => "Lỗi. Chỉ hỗ trợ dạng: png, gif, jpg, bmp và dưới {$maxFileSize}Mb",
                        )
                    )
                );
                echo json_encode($data);
                die;
            }

            Yii::import('ext.wideimage.lib.WideImage');

            $imgConf = Yii::app()->params->hangve['post'];
            $item_id = Yii::app()->request->getQuery('id'); // is post id or reply id

            // update action
            if($item_id){
                $imgPath = $_FILES["files"]["tmp_name"][0];

                $item = ($type == 'post') ? Post::model()->findByPk($item_id) : PostReply::model()->findByPk($item_id);
                if(!$item){
                    $data = array(
                        'files' => array(
                            array(
                                'name' => $_FILES["files"]["name"][0],
                                'size' => $_FILES["files"]["size"][0],
                                'type' => $_FILES["files"]["type"][0],
                                'error' => "Yêu cầu không hợp lệ",
                            )
                        )
                    );
                    echo json_encode($data);
                }
                $fileName = ($type == 'post' ? $item->alias : $item->post->alias).'_'.PostImage::model()->nextId;
                $savedPath = $item->getImagePath(); 


                $this->_saveTypeImage($imgPath, $imgConf, $savedPath, $fileName);

                // insert to DB
                $itemImage = new PostImage;
                $itemImage->post_id = ($type == 'post') ? $item_id : $item->post_id;
                $itemImage->reply_id = ($type == 'post') ? null : $item->id;
                $itemImage->user_id = $this->user->id;
                $itemImage->image = $fileName;
                $itemImage->is_cover = 0;
                $itemImage->insert();

                $data = array(
                    'files' => array(
                        array(
                            'id' => $itemImage->image,
                            'name' => $itemImage->image.'.jpg',
                            'url' => $itemImage->url,
                            'url_thumb' => $itemImage->getUrl('small'),
                            'delete_url' => $this->createAbsoluteUrl("/hangve/post/upload", array('id' => $itemImage->id, 'type' => $type)),
                            'delete_method' => 'DELETE',
                        )
                    )
                );

            }
            // create action
            else{
                $tempPath = ($type == 'post') ? $imgConf['tempPath'] : $imgConf['tempPathReply'];
                $tempPath = "{$tempPath}{$this->user->id}/";

                Myext::createDir($tempPath);
                $fileId = uniqid();
                $fileName = $fileId.'.jpg';

                $imgObj = WideImage::load($_FILES["files"]["tmp_name"][0]);

                $imgLarge = Yii::app()->params->hangve['post']['img']['large'];
                $imgSmall = Yii::app()->params->hangve['post']['img']['small'];

                $imgObj = $imgObj->resize(null, $imgLarge['height'], 'outside', 'down');
                $imgObj = $imgObj->crop('center', 'center', $imgLarge['width'], $imgLarge['height']);

                $imgObj->saveToFile($tempPath.$fileName, 95);  

                $data = array(
                    'files' => array(
                        array(
                            'id' => $fileId,
                            'name' => $fileName,
                            'size' => $_FILES['files']["size"][0],
                            'type' => $_FILES['files']["type"][0],
                            'url' => $this->baseUrl.'/'.$tempPath.$fileName,
                            'url_thumb' => $this->createAbsoluteUrl("/common/imageThumb", array('path' => $tempPath.$fileName, 'w' => $imgSmall['width'], 'h' => $imgSmall['height'])),
                            'delete_url' => $this->createAbsoluteUrl("/hangve/post/upload", array('path' => $tempPath.$fileName, 'type' => $type)),
                            'delete_method' => 'DELETE',
                        )
                    )
                ); 

                // update session image
                $imgTemp = Yii::app()->session[$sessionKey];
                $imgTemp = $imgTemp ? array_merge($imgTemp, array($tempPath.$fileName)) : array($tempPath.$fileName);
                Yii::app()->session[$sessionKey] = $imgTemp;
            }
            echo json_encode($data); 
            die;
        }

        private function _uploadDelete($type, $sessionKey){
            $path = Yii::app()->request->getQuery('path');
            $imgId = Yii::app()->request->getQuery('id');

            if($imgId){

                $itemImage = PostImage::model()->with('post')->findByPk($imgId);
                $post = $itemImage->post;

                $imgConf = Yii::app()->params->hangve['post'];
                foreach(array_keys($imgConf['img']) as $type){
                    Myext::deleteFile(ltrim($itemImage->getUrl($type), '/'));
                }
                $itemImage->delete();

                // Nếu ảnh bị xóa là ảnh đại diện thì cập nhật ảnh đầu tiên là ảnh đại diện.
                $post->image = null;
                if($itemImage->is_cover && !empty($post->postImages[0])){
                    $firstPostImage = $post->postImages[0];
                    $firstPostImage->is_cover = 1;
                    $firstPostImage->update();
                    $post->image = $firstPostImage->image;
                }
                $post->update();


            }else{
                // update session image
                $imgTemp = Yii::app()->session[$sessionKey];

                array_diff($imgTemp, array($path));
                Yii::app()->session[$sessionKey] = $imgTemp;
                Myext::deleteFile($path);
            }

            echo json_encode(array('success' => TRUE));

        }

        private function _uploadGet($type, $sessionKey){
            $itemId = Yii::app()->request->getQuery('id');
            $coverSaved = Yii::app()->request->getQuery('cover');

            if($itemId){
                $images = ($type == 'post') ? 
                PostImage::model()->findAllByAttributes(array('post_id' => $itemId, 'reply_id' => null)) :
                PostImage::model()->findAllByAttributes(array('reply_id' => $itemId));

                $data = array();
                foreach($images as $img){
                    $data['files'][] = array(
                        'id' => $img->id,
                        'name' => $img->image.'.jpg',
                        'is_cover' => $img->is_cover,
                        'url' => $img->url,
                        'url_thumb' => $img->getUrl('small'),
                        'delete_url' => $this->createAbsoluteUrl("/hangve/post/upload", array('id' => $img->id, 'type' => $type)),
                        'delete_method' => 'DELETE',
                    ); 
                }

            }else{
                $imgSmall = Yii::app()->params->hangve['post']['img']['small'];
                $imgTemp = Yii::app()->session[$sessionKey];
                $imgTempExist = array();
                $data = array();
                if($imgTemp){

                    foreach($imgTemp as $path){
                        if(file_exists($path)){
                            $imgTempExist[] = $path;

                            $img = getimagesize($path);
                            $info = pathinfo($path);

                            $is_cover = ($coverSaved && $coverSaved == $info['filename']) ? 1 : 0;
                            if(!empty(Yii::app()->request->cookies['post_img_cover']->value)){
                                $is_cover = Yii::app()->request->cookies['post_img_cover']->value == $info['filename'] ? 1 : 0;
                            }

                            $fileData = array(
                                'id' => $info['filename'],
                                'name' => $info['basename'],
                                'is_cover' => $is_cover,
                                'size' => filesize($path),
                                'type' => $img['mime'],
                                'url' => $this->baseUrl.'/'.$path,

                                'url_thumb' => $this->createAbsoluteUrl("/common/imageThumb", array('path' => $path, 'w' => $imgSmall['width'], 'h' => $imgSmall['height'])),
                                'delete_url' => $this->createAbsoluteUrl("/hangve/post/upload", array('path' => $path, 'type' => $type)),
                                'delete_method' => 'DELETE',
                            );
                            $data['files'][] = $fileData;
                        }
                    } 
                }

                Yii::app()->session[$sessionKey] = $imgTempExist;    
            }
            echo json_encode($data); 

        }

    }
